<template>
	<!-- <u-navbar title="查询分页列表" bgColor="#FBFBFF" :autoBack="true" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
	</u-navbar> -->
	<view class="baseForm">
		<u--form labelPosition="left" labelWidth="100px">
			<u-form-item label="扫描条形码">
				<!-- 条码录入 -->
				<scan-bar ref="scanBarRef" @code-scanned="getScanResult" class="scan-bar"></scan-bar>
			</u-form-item>
		</u--form>
		<view class="list" style="height: 60px;" v-if="workOrderList[0].id">
			<view class="card">
				<view style="width: 100%;font-weight: 700; font-size: 16px;">
					<!-- <view class="des">当前批次计划加工单Id：{{workOrderList[0]?.plannedBatchId || ''}}</view> -->
					<!--<view class="des">
						半成品物料：<template v-for="(item, index) in workOrderList[0]?.productionMaterialCodes" :key="index">
							{{ workOrderList[0]?.productionMaterialCodes[index] || '' }}-{{ workOrderList[0]?.productionMaterialNames[0] || '' }}
							&nbsp;</template>
					</view> -->
					<view class="des">总成物料：{{ workOrderList[0]?.materialCode || '' }}-{{ workOrderList[0]?.materialName || '' }}</view>
					<!-- <view class="des">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：
						<template v-for="(item, index) in workOrderList[0]?.productionMaterialFigureNumbers"
							:key="index">
							{{ item || '' }} &nbsp;</template>
					</view> -->
					<view class="des">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：{{ workOrderList[0]?.productionMaterialFigureNumber || '' }}-{{ workOrderList[0]?.materialName || '' }}</view>
				</view>
			</view>
		</view>
		<u-button size="large" type="primary" text="报工" @click="jumpToDetail('','报工新增','2','0')" :throttleTime="10000"></u-button>
		<!-- 卡片显示 -->
		<text class="list-title">列表信息({{ total }})</text>
		<view class="activeHeight">
			<!-- 列表 -->
			<u-list  @scrolltolower="scrolltolower" class="list" v-if="total" :height="listHeight" lowerThreshold="100px">
				<u-list-item v-for="(item, index) in materialReturnList" :key="item.id">
					<view class="card">
						<view class="right">
							<view class="title1">
								周转码:{{ item?.produceTransferFormCode || '' }}
							</view>
							<view class="des">{{ item?.materialCode || 0 }}{{ item?.materialName || 0 }}</view>
							<view class="des" v-if="item.isValid==1">合格件数：{{ item?.productQuantity || '0' }}</view>
							<view class="des" v-else>不合格数：{{ item?.productQuantity || '0' }}</view>
							<view class="des">报工时间：{{ item?.lastUpdateTime || '待定' }}</view>
						</view>
						<view class="left">
							<view class="title">
								<!-- <button v-show="item?.isReturn" class="uni-btn" size="mini" type="primary">已退</button> -->
								<button class="uni-btn" size="mini" plain type="primary"
									@click="selectWorkOrder(item, index)">打印</button>
							</view>
							<view class="des">批次：{{ item?.remarks || "" }}</view>
							<view class="des">单位：{{ item?.quantityUnit || 0 }}</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>
		<!-- 动态创建webview -->
<!-- 		<web-view v-if="showWebView" :src="webviewSrc" :update-title="false" allow="*"
			style="width: 0;height: 0"></web-view> -->
		<!-- <web-view v-if="showWebView" :src="webviewSrc" :update-title="false" allow="*" @load="handleMessage"></web-view> -->
		<web-view
			ref="webview"
			v-if="showWebView"
			:src="webviewSrc"
			:update-title="false"
			:webview-styles="{
				width: '0px',
				height:'0px',
			}"
			style="height:0px;width:0px;background-color: aquamarine;"
			@message="message"
		></web-view>
		<u-modal :show="showImport" ref="uModal" :content="`当前外部编号为${selectOrder?.externalCode ?? ''}, 请确认是否打印？`"
			confirmText="打印" showCancelButton :asyncClose="true" @cancel="cancelImport"
			@confirm="confirmImport(selectOrder.id)"></u-modal>
	</view>
	<u-back-top :scroll-top="scrollTop" top="200" mode="squery"></u-back-top>
</template>

<script lang="ts" setup>
	import { computed, ref, watch } from 'vue';
	import { onPageScroll, onPullDownRefresh, onShow } from '@dcloudio/uni-app';
	import ScanBar from '@/components/scan-bar/index.vue';
	import { http } from '@/utils/http';
	import { PageResult } from '@/types/type';
	import { useUserStore } from '../../../stores/useUserStore';
	import { useProduceStore } from '../../../stores/useProduceStore';
	import { useDictionaryStore } from '../../../stores/useDictionaryStore';
	// loginWorkInfo
	const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
	// 加工单信息
	const workOrderList = computed(() => JSON.parse(useProduceStore().workOrderList));
	console.log(workOrderList.value)
	// 监听页面到顶部距离
	const scrollTop = ref(0)
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop
	})
	onShow(async () => {
		// #ifdef H5
		listHeight.value = 'calc(100vh - 88px)';
		// #endif
		
		// #ifdef APP-PLUS
		listHeight.value = 'calc(100vh - 44px)';
		// #endif
		current.value = 0;		//分页第一页
		materialReturnList.value = [];	//数据清空
		getMaterialReturnList()

	})
	// 获取扫码结果

	function getScanResult(result : string) {
		if (result != "") {
			let isValid = ref("2")
			// 获取code码详细信息，并进行赋值
			let index = materialReturnList.value.findIndex((item) => item.externalCode == result)
			console.log(index);
			if (index == -1) {
				uni.$u.toast('请扫描正确编码');
			}
			let sumQuantity = 0
			for (let i = 0; i < materialReturnList.value.length; i++) {

				if (materialReturnList.value[i].externalCode == result) {
					isValid.value = materialReturnList.value[i].isValid
					code.value = result;
					sumQuantity = materialReturnList.value[i].productQuantity + sumQuantity
				}
			}
			jumpToDetail(result, '二次报工', isValid.value, sumQuantity + "")
			isValid.value = "2"
			reset();
		}

	}

	// 跳转至详情页面
	function jumpToDetail(result ?: string, title ?: string, isValid ?: string, sumQuantity ?: string) {
		http({
			method: 'POST',
			url: '/wms/wmspackagecmd/getList',
			data: {
				materialId: workOrderList.value[0].productionMaterialId,
				applicableScenario: 5,
			}
		}).then((res) => {
			if (res.code == '200') {
				// if (res.data[0]?.quantity >= 0) {
					if (workOrderList.value[0]?.id) {
						uni.navigateTo({
							url: `/pages/produce/produceTransferForm/detail?result=${result}&title=${title}&isValid=${isValid}&sumQuantity=` + sumQuantity
						});
					} else {
						uni.$u.toast('请选择加工单进行报工');
					}
				// } else {
				// 	uni.$u.toast('包装指令不存在，不可以报工。');
				// }
			} else {
				uni.$u.toast(res.message);
			}

		})

	}

	// 请求列表参数定义
	const materialReturnList = ref([]); // 缺货要货集合
	const current = ref(0); // 当前页
	const totalPage = ref(0); //累计分页
	const total = ref(0); // 累计条数
	const code = ref(''); // 扫码结果

	// 初始化参数
	function reset() {
		current.value = 0;
		materialReturnList.value = [];
		total.value = 0;
		totalPage.value = 0;
	}
	onPullDownRefresh(() => {
		current.value = 0;		//分页第一页
		materialReturnList.value = [];	//数据清空
		getMaterialReturnList('refresh');	//数据请求
	})
	//打印日志信息
	const operateLog = ref({
		logLevel: "INFO",
		applicationName: "jcfk-mes",
		modular: "报工开始",
		businessType: "打印",
		info: "",
	})
	async function getMaterialReturnList(type ?: string) {
		try {
			current.value += 1;
			const result : PageResult<any> = await http({
				method: 'POST',
				url: '/mes/mesproducereport/queryByPage',
				data: {
					current: current.value,
					size: 20,
					data: {
						workCenterId: loginWorkInfo.value.workCenterId,
            workOrderId: workOrderList.value[0]?.id,
            plannedBatchId: workOrderList.value[0]?.id,
					}
				}
			});
			let list = result.data;
			list.forEach((i)=>{
				materialReturnList.value.push(i)
			})
			materialReturnList.value.forEach(item => {
				if (Number(item.quantityUnit) && !isNaN(Number(item.quantityUnit))) {
					item.quantityUnit = useDictionaryStore().filterDictName("MeasurementUnit", item.quantityUnit)
				}
			});
			total.value = result.total;
			totalPage.value = result.page;
			type === 'refresh' && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
	// 选择订单
	const selectOrder = ref({});
	const selectIndex = ref();
	const showImport = ref(false);
	const showWebView = ref(false);
	function selectWorkOrder(row, index) {
		showWebView.value = true;
		const defaultPrinter = computed(() => (useUserStore().defaultPrinter ? JSON.parse(useUserStore().defaultPrinter) : ''));
		console.log("111",defaultPrinter.value.printerName);
		if (defaultPrinter.value.length==0)
		{
		uni.showToast({
			title: '请选择打印设备',
			icon: 'error'
		});
		return false;
		}
		else
		{
		showImport.value = true;
		selectOrder.value = row;
		selectIndex.value = index;
		}
	}
	// 取消选择订单
	function cancelImport() {
		showImport.value = false;
		selectOrder.value = {};
		selectIndex.value = null;
	}

	function handleMessage(e) {
		console.log('收到来自webview的消息:', e.detail);
	}

	// 打印功能
	const url = process.env.VITE_APP_WEBVIEW;
	const webviewSrc = ref(url);
	function confirmImport(id) {
		const defaultPrinter = computed(() => JSON.parse(useUserStore().defaultPrinter));
		const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
		setTimeout(()=>{
			insertOperateLog(id,defaultPrinter.value.printerName)
			webviewSrc.value = `${url}iframePrint?id=${id}&printer=${defaultPrinter.value.printerName}&printername=${loginWorkInfo.value.userName}`
			console.log(webviewSrc.value)
		},1000)
	}
	//开始打印
	async function insertOperateLog(id : any, name : any) {
		operateLog.value.info = id + "," + name
		await http({
			method: 'POST',
			url: '/system/sysOperateLog/insert',
			data: operateLog.value
		});
	}
	//列表高度
	const listHeight = ref('');
	const scrolltolower = () => {
		totalPage.value > current.value && getMaterialReturnList();
	};
	//打印
	watch(()=>showImport.value,(newValue)=>{
		if (newValue === false) {
			showWebView.value = false;
			webviewSrc.value = url;
			selectOrder.value = {};
		}
	})
	// webview向外部发送消息
	function message(event) {
		console.log("event",event)
		showImport.value = false;
		const data = event.detail.data[0];
		if (data.code === 200) {
			uni.showToast({
				icon: 'none',
				title:data.message,
			})
		} else {
			uni.showToast({
				icon: 'none',
				title:data.message,
			})
		}
		console.log("接收到消息：" + JSON.stringify(event.detail.data));
	}
</script>

<style lang="scss" scoped>
	.baseForm {
		:deep(.uni-scroll-view) {
			overflow: inherit;
		}

		.u-form {
			padding: $uni-page-padding;

			:deep(.u-form-item__body) {
				padding: 5px 0;
			}

			.u-input {
				border: 1px solid $uni-input-border-color;
			}

			.scan-bar {
				margin-top: 5px;
				display: flex;
				flex: 1;
			}
		}

		.u-line {
			padding: 10px 0;
		}

		.search {
			display: flex;

			.custom-style {
				// width: 120px;
				margin: 10px 5px 5px;
				height: 36px;
				border-radius: 8px;

				&:nth-child(1) {
					flex: 1
				}

				&:nth-child(2) {
					flex: 3
				}
			}
		}

		.list-title {
			line-height: 40px;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.4);
			margin-left: 15px;
		}

		.list {
			.card {
				margin: $uni-page-padding;
				margin-top: 5px;
				margin-bottom: 5px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				padding: 1px 10px 0px 10px;
				transition: all 300ms ease;
				box-shadow: 0 1px 5px rgba(19, 11, 236, 0.13);
				background-color: #fff;
				display: flex;
				align-items: flex-start;

				.left {
					flex: 1;
					margin-left: -53px;
				}

				.title {
					font-size: 14px;
					line-height: 40px;
					height: 37px;
					margin-top: 0px;

					color: #101010;
					border-bottom: 1px solid #E5EBFF;
				}

				.title1 {
					font-size: 12px;
					line-height: 40px;
					height: 37px;
					margin-top: 0px;
					width: 200px;
					color: #101010;
					border-bottom: 1px solid #E5EBFF;
					font-weight: 700;
				}

				.uni-btn {
					float: right;
					font-size: 12px;
					height: 24px;
					line-height: 24px;
					padding: 0 15px;
					margin-top: 7px;
					font-weight: 400;
				}

				.des {
					font-size: 12px;
					line-height: 20px;
					height: 20px;
					margin-top: 3px;
					margin-bottom: 3px;
				}

				.right {
					// flex: 1;
					flex-basis: calc(60% + 10px);
				}
			}
		}
	}
</style>